﻿using AutoMapper;
using Newtonsoft.Json;
using StarsAdmin.Application.User.Dtos;
using StarsAdmin.Core.DB.Entities;
using StarsAdmin.Core.Helpers;
using StarsAdmin.Core.Models;

namespace StarsAdmin.Application.User.Mappings
{
    public class UserAutoMapperProFile : Profile
    {
        public UserAutoMapperProFile()
        {
            CreateMap<Page<UserEntity>, Page<UserDto>>();

            CreateMap<AddUserInput, UserEntity>()
                .ForMember(dest => dest.Address, opt => opt.MapFrom(src => JsonConvert.SerializeObject(src.Address)))
                .ForMember(dest => dest.PasswordSalt, opt => opt.MapFrom(src => StringHelper.GenerateRandomString(5)))
                .ForMember(dest => dest.PasswordHash, opt => opt.MapFrom((src, dest) => MD5Helper.MD5Encrypt32(dest.PasswordSalt + (src.Password ?? "123456"))));

            CreateMap<UpdateUserInput, UserEntity>()
                .ForMember(dest => dest.Address, opt => opt.MapFrom(src => JsonConvert.SerializeObject(src.Address)))
                .ForMember(dest => dest.PasswordSalt, opt => opt.MapFrom((src, dest) => string.IsNullOrWhiteSpace(src.Password) ? dest.PasswordSalt : StringHelper.GenerateRandomString(5)))
                .ForMember(dest => dest.PasswordHash, opt => opt.MapFrom((src, dest) => string.IsNullOrWhiteSpace(src.Password) ? dest.PasswordHash : MD5Helper.MD5Encrypt32(dest.PasswordSalt + src.Password)));

            CreateMap<UserEntity, ExportUserDto>()
                .ForMember(dest => dest.Address, opt => opt.MapFrom(src => ParerAddress(src.Address)));

            CreateMap<UserEntity, UserDto>()
                .ForMember(dest => dest.Address, opt => opt.MapFrom(src => JsonConvert.DeserializeObject(src.Address)))
                .ForMember(dest => dest.RoleIds, opt => opt.MapFrom(src => src.Roles.Select(e => e.Id)));
        }

        private string ParerAddress(string address)
        {
            var parerAddress = JsonConvert.DeserializeObject<string[]>(address);
            if (parerAddress == null)
            {
                return string.Empty;
            }
            var result = "";
            foreach (var item in parerAddress)
            {
                result = result == "" ? item : result + " - " + item;
            }
            return result;
        }
    }
}